package com.stock.demo.util;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by XuZhaoyu on 2017/7/31.
 */

public class SpanResource {
    private static final String RICH_BROW = "<IMG src=\"emotion\\%s\" custom=\"false\">";
    public static String matchString;
    private static Map<String, Drawable> uiMap;
    private static Map<String, Integer> browMap;
    private static Map<String, String> richSendMap;
    private static Map<String, String> textMap;
    private static Map<String, Drawable> gifMap;
    private static List<String> textTipList;
    public static final int CONTEXT_MAX = 512;
    public static final int CONTEXT_AVATAR_MAX = 20;
    private static Html.ImageGetter extraImageGetter = null;

    public SpanResource() {
    }

    public static void setExtraImageGetter(Html.ImageGetter extraImageGetter) {
        SpanResource.extraImageGetter = extraImageGetter;
    }

    public static Map<String, Drawable> getBrowMap(Context context) {
        return uiMap;
    }

    public static void initTextTipList(List<String> textList) {
        if (textTipList == null) {
            textTipList = new ArrayList();
        }

        textTipList.clear();
        textTipList.addAll(textList);
    }

    public static void initTextMap(HashMap<String, String> mapValue) {
        if (textMap == null) {
            textMap = new HashMap(18);
        }

        textMap.clear();
        textMap.putAll(mapValue);
    }

    public static void initUiMap(HashMap<String, Drawable> mapValue) {
        if (uiMap == null) {
            uiMap = new LinkedHashMap(18);
        }

        uiMap.clear();
        uiMap.putAll(mapValue);
    }

    public static void initBrowSource(LinkedHashMap<String, Integer> mapValue) {
        if (browMap == null) {
            browMap = new LinkedHashMap(18);
        }

        browMap.clear();
        browMap.putAll(mapValue);
    }

    public static void putGifDrawable(String key, Drawable gifDrawable) {
        if (gifMap == null) {
            gifMap = new HashMap(18);
        }

        gifMap.put(key, gifDrawable);
    }

    public static void initSendRichMap(HashMap<String, String> mapValue) {
        if (matchString == null) {
            matchString = initMachString(uiMap.keySet());
            matchString = matchString.substring(0, matchString.length() - 1);
        }

        if (richSendMap == null) {
            richSendMap = new HashMap(18);
        }

        richSendMap.clear();
        richSendMap.putAll(mapValue);
    }

    private static synchronized String initMachString(Set<String> keyset) {
        StringBuilder sb = new StringBuilder();
        Iterator var3 = keyset.iterator();

        while (var3.hasNext()) {
            String key = (String) var3.next();
            sb.append(key).append('|');
        }

        return sb.toString();
    }

    public static Spannable convetToSpan(String content, Context context) {
        StringBuilder sb = new StringBuilder();
        sb.append(' ').append(content).toString();
        SpannableStringBuilder spBuilder = new SpannableStringBuilder(content);
        if (uiMap != null && uiMap.size() > 0) {
            Pattern mPattern = Pattern.compile(matchString);
            Matcher matcher = mPattern.matcher(content);

            while (matcher.find()) {
                Drawable drawable = (Drawable) uiMap.get(matcher.group());
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                ImageSpan ispan = new ImageSpan(drawable, 0);
                spBuilder.setSpan(ispan, matcher.start(), matcher.end(), 33);
            }

            return spBuilder;
        } else {
            return spBuilder;
        }
    }

    public static int[] getAvatarCount(String content) {
        int[] nCount = new int[3];
        if (matchString != null) {
            StringBuilder sb = new StringBuilder();
            sb.append(' ').append(content).toString();
            Pattern mPattern = Pattern.compile(matchString);

            for (Matcher matcher = mPattern.matcher(content); matcher.find(); nCount[2] = matcher.group().length()) {
                ++nCount[0];
                nCount[1] += matcher.group().length();
            }
        }

        return nCount;
    }

    public static Spanned convetRichToExpression(Context context, String rich, int start, Map<Integer, Drawable> cache, final Vector<Drawable> drawables) {
        if (uiMap != null && uiMap.size() > 0) {
            return Html.fromHtml(rich, new Html.ImageGetter() {
                public Drawable getDrawable(String source) {
                    if (source == null) {
                        return null;
                    } else {
                        int index = source.lastIndexOf("\\");
                        String lastStr = source.substring(index + 1);
                        String keyStr = "【" + lastStr + "】";
                        Drawable mSmile = null;
                        if (source.endsWith(".gif")) {
                            if (SpanResource.gifMap != null) {
                                mSmile = (Drawable) SpanResource.gifMap.get(keyStr);
                                if (drawables != null && !drawables.contains(mSmile)) {
                                    drawables.add(mSmile);
                                }
                            } else {
                                SpanResource.log("convetRichToExpression", "gifMap is null, that expression un install");
                            }
                        } else if (SpanResource.uiMap != null) {
                            mSmile = (Drawable) SpanResource.uiMap.get(keyStr);
                        } else {
                            SpanResource.log("convetRichToExpression", "uiMap is null, that expression un install");
                        }

                        if (mSmile == null && SpanResource.extraImageGetter != null) {
                            mSmile = SpanResource.extraImageGetter.getDrawable(source);
                        }

                        return mSmile;
                    }
                }
            }, (Html.TagHandler) null);
        } else {
            SpannableStringBuilder spBuilder = new SpannableStringBuilder(rich);
            return spBuilder;
        }
    }

    public static String convertToSendText(String content) {
        if (textMap != null && textMap.size() > 0) {
            Pattern mPattern = Pattern.compile(matchString);

            for (Matcher matcher = mPattern.matcher(content); matcher.find(); content = content.replace(matcher.group(), (CharSequence) textMap.get(matcher.group()))) {

            }

            return content;
        } else {
            return content;
        }
    }

    public static String convertToSendRichText(String content) {
        if (textTipList != null && textTipList.size() > 0 && richSendMap != null && richSendMap.size() > 0 && textMap != null && textMap.size() > 0) {
            content = escapeStr(content);
            Pattern mPattern = Pattern.compile(matchString);
            Matcher matcher = mPattern.matcher(content);

            while (true) {
                while (matcher.find()) {
                    if (textTipList.contains(matcher.group()) && !content.contains(matcher.group() + (String) textMap.get(matcher.group()))) {
                        content = content.replace(matcher.group(), String.format("<IMG src=\"emotion\\%s\" custom=\"false\">", new Object[]{richSendMap.get(matcher.group())}) + (String) textMap.get(matcher.group()));
                    } else {
                        content = content.replace(matcher.group(), String.format("<IMG src=\"emotion\\%s\" custom=\"false\">", new Object[]{richSendMap.get(matcher.group())}));
                    }
                }

                StringBuilder sReturn = new StringBuilder();
                sReturn.append("<SPAN>");
                sReturn.append(content);
                sReturn.append("</SPAN>");
                return sReturn.toString();
            }
        } else {
            return content;
        }
    }

    private static String escapeStr(String content) {
        String sReturn = content;
        if (content.contains("&")) {
            sReturn = content.replace("&", "&amp;");
        }

        if (sReturn.contains("<")) {
            sReturn = sReturn.replace("<", "&lt;");
        }

        if (sReturn.contains(">")) {
            sReturn = sReturn.replace(">", "&gt;");
        }

        if (sReturn.contains(" ")) {
            sReturn = sReturn.replace(" ", "&nbsp;");
        }

        if (content.contains("\n")) {
            sReturn = sReturn.replace("\n", "<br>");
        }

        return sReturn;
    }

    private static void log(String func, String msg) {
        Log.w("Gensee", func + " > " + msg);
    }
}
